package com.logistics.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.logistics.common.Constants;
import com.logistics.common.TenantContextHolder;
import com.logistics.entity.SysDictionary;
import com.logistics.mapper.SysDictionaryMapper;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 字典服务
 */
@Service
public class DictionaryService {
    
    private final SysDictionaryMapper dictionaryMapper;
    
    public DictionaryService(SysDictionaryMapper dictionaryMapper) {
        this.dictionaryMapper = dictionaryMapper;
    }
    
    /**
     * 获取某类型的字典列表（仅返回启用的）
     * 用于新增数据时的下拉选项
     */
    public List<SysDictionary> getDictionaryByType(String dictType) {
        Long tenantId = TenantContextHolder.getTenantId();
        
        LambdaQueryWrapper<SysDictionary> wrapper = new LambdaQueryWrapper<>();
        // 租户可以使用：
        // 1）平台预置系统字典（tenant_id = 0, is_system = 1）
        // 2）本租户自定义字典（tenant_id = 当前租户）
        wrapper.in(SysDictionary::getTenantId, Constants.PLATFORM_TENANT_ID, tenantId)
               .eq(SysDictionary::getDictType, dictType)
               .eq(SysDictionary::getStatus, 1)
               .orderByAsc(SysDictionary::getTenantId, SysDictionary::getSortOrder);
        
        return dictionaryMapper.selectList(wrapper);
    }
    
    /**
     * 获取某类型的所有字典列表（包括已禁用的）
     * 用于显示历史数据，确保已删除的字典项也能正确显示标签
     */
    public List<SysDictionary> getAllDictionaryByType(String dictType) {
        Long tenantId = TenantContextHolder.getTenantId();
        
        LambdaQueryWrapper<SysDictionary> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SysDictionary::getTenantId, Constants.PLATFORM_TENANT_ID, tenantId)
               .eq(SysDictionary::getDictType, dictType)
               .orderByAsc(SysDictionary::getTenantId, SysDictionary::getSortOrder);
        
        return dictionaryMapper.selectList(wrapper);
    }
    
    /**
     * 获取所有字典（按类型分组）
     * 用于字典管理页面，需要显示所有字典（包括禁用的）以便管理
     */
    public List<SysDictionary> getAllDictionaries() {
        Long tenantId = TenantContextHolder.getTenantId();
        
        LambdaQueryWrapper<SysDictionary> wrapper = new LambdaQueryWrapper<>();
        // 字典管理页面需要看到：平台预置 + 本租户自定义
        wrapper.in(SysDictionary::getTenantId, Constants.PLATFORM_TENANT_ID, tenantId)
               .orderByAsc(SysDictionary::getDictType, SysDictionary::getTenantId, SysDictionary::getSortOrder);
        
        return dictionaryMapper.selectList(wrapper);
    }
    
    /**
     * 添加自定义字典
     */
    public SysDictionary addDictionary(SysDictionary dictionary) {
        Long tenantId = TenantContextHolder.getTenantId();
        
        // 如果未提供dictCode，自动生成
        if (dictionary.getDictCode() == null || dictionary.getDictCode().isEmpty()) {
            dictionary.setDictCode(generateDictCode(tenantId, dictionary.getDictType()));
        }
        
        // 检查代码是否重复
        LambdaQueryWrapper<SysDictionary> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDictionary::getTenantId, tenantId)
               .eq(SysDictionary::getDictType, dictionary.getDictType())
               .eq(SysDictionary::getDictCode, dictionary.getDictCode());
        
        if (dictionaryMapper.selectCount(wrapper) > 0) {
            throw new RuntimeException("字典代码已存在");
        }
        
        dictionary.setTenantId(tenantId);
        dictionary.setIsSystem(0);  // 租户自定义
        dictionaryMapper.insert(dictionary);
        
        return dictionary;
    }
    
    /**
     * 生成字典代码
     */
    private String generateDictCode(Long tenantId, String dictType) {
        // 查询当前类型下的字典数量，生成序号
        LambdaQueryWrapper<SysDictionary> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDictionary::getTenantId, tenantId)
               .eq(SysDictionary::getDictType, dictType);
        
        long count = dictionaryMapper.selectCount(wrapper);
        
        // 生成格式：CUSTOM_001, CUSTOM_002...
        return String.format("CUSTOM_%03d", count + 1);
    }
    
    /**
     * 更新字典
     */
    public void updateDictionary(Long id, SysDictionary dictionary) {
        SysDictionary existing = dictionaryMapper.selectById(id);
        if (existing == null) {
            throw new RuntimeException("字典不存在");
        }
        
        // 系统预置字典不允许修改
        if (existing.getIsSystem() == 1) {
            throw new RuntimeException("系统预置字典不允许修改");
        }
        
        // 更新字段
        if (dictionary.getDictLabel() != null) {
            existing.setDictLabel(dictionary.getDictLabel());
        }
        if (dictionary.getDictValue() != null) {
            existing.setDictValue(dictionary.getDictValue());
        }
        if (dictionary.getSortOrder() != null) {
            existing.setSortOrder(dictionary.getSortOrder());
        }
        if (dictionary.getRemark() != null) {
            existing.setRemark(dictionary.getRemark());
        }
        if (dictionary.getStatus() != null) {
            existing.setStatus(dictionary.getStatus());
        }
        
        dictionaryMapper.updateById(existing);
    }
    
    /**
     * 删除字典（软删除，设置为禁用状态）
     * 保留记录以确保历史数据能正常显示
     */
    public void deleteDictionary(Long id) {
        SysDictionary dictionary = dictionaryMapper.selectById(id);
        if (dictionary == null) {
            throw new RuntimeException("字典不存在");
        }
        
        // 系统预置字典不允许删除
        if (dictionary.getIsSystem() == 1) {
            throw new RuntimeException("系统预置字典不允许删除");
        }
        
        // 软删除：设置状态为0（禁用）
        // 这样历史订单仍能通过代码查到对应的标签
        // 但新订单的下拉选项中不会显示（因为getDictionaryByType只查status=1的）
        dictionary.setStatus(0);
        dictionaryMapper.updateById(dictionary);
    }
}

